<template>
  <div class="question-new-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ cardTitle }}</span>
      </div>
      <!-- 表单 -->
      <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="form.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="changeSubject"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="form.catalogID" placeholder="请选择" style="width: 400px">
            <el-option
              v-for="item in catalogList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择" style="width: 400px">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市：" style="width: 520px" prop="questionType">
          <el-col :span="12">
            <el-form-item prop="province">
              <el-select
                v-model="form.province"
                placeholder="请选择"
                style="width: 98%"
                @change="changeProvince"
              >
                <el-option
                  v-for="item in provinceList"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="city">
              <el-select
                v-model="form.city"
                placeholder="请选择"
                style="width: 98%; margin-left: 4px"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="form.direction" placeholder="请选择" style="width: 400px">
            <el-option
              v-for="item in directionList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio
            v-for="item in questionTypeArr"
            :key="item.value"
            v-model="form.questionType"
            :label="item.value"
            @change="questionTypeChange"
            >{{ item.label }}</el-radio
          >
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio
            v-for="item in difficultyArr"
            :key="item.value"
            v-model="form.difficulty"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干：" prop="question" ref="questionRef">
          <!-- 富文本编辑器 -->
          <quill-editor
            v-model="form.question"
            :options="editorOption"
            @change="changeQuillEditor('question')"
            @blur="changeQuillEditor('question')"
          ></quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项：" v-show="form.questionType !== 3">
          <template v-if="form.questionType === 1">
            <div class="option_item" v-for="item in form.options" :key="item.code">
              <el-radio v-model="currentRadio" :label="item.code" @change="radioChange"
                >{{ item.code }}:</el-radio
              >
              <questions-new-option v-model="item.title" :img-url="item.img"></questions-new-option>
            </div>
          </template>
          <template v-else>
            <div class="option_item" v-for="item in form.options" :key="item.code">
              <el-checkbox v-model="item.isRight" :label="item.code">{{ item.code }}:</el-checkbox>
              <questions-new-option v-model="item.title" :img-url="item.img"></questions-new-option>
            </div>
          </template>
        </el-form-item>
        <!-- 新增选项与答案 -->
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-plus"
            v-show="form.questionType !== 3"
            :disabled="form.questionType === 1"
            @click="addOption"
            >新增选项与答案</el-button
          >
        </el-form-item>
        <!-- 视频 -->
        <el-form-item label="解析视频:">
          <el-input v-model="form.videoURL" style="width: 400px"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析：" prop="answer" ref="answerRef">
          <!-- 富文本编辑器 -->
          <quill-editor
            v-model="form.answer"
            :options="editorOption"
            @change="changeQuillEditor('answer')"
            @blur="changeQuillEditor('answer')"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：">
          <el-input type="textarea" v-model="form.remarks" style="width: 400px"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select v-model="form.tags" placeholder="请选择试题标签" multiple style="width: 400px">
            <el-option
              v-for="item in tagList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 确认提交 -->
        <el-form-item>
          <el-button
            :type="this.cardTitle === '试题录入' ? 'primary' : 'success'"
            @click="onSubmit"
            >{{ this.cardTitle === '试题录入' ? '确认提交' : '确认修改' }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import QuestionsNewOption from '@/module-hmmm/components/questions-new-option'
import { simple as fetchSubjects } from '@/api/hmmm/subjects.js'
import { list as fetchCompanys } from '@/api/hmmm/companys.js'
import { provinces as fetchProvinces, citys as fetchCitys } from '@/api/hmmm/citys.js'
import { simple as fetchDirectorys } from '@/api/hmmm/directorys.js'
import { simple as fetchTags } from '@/api/hmmm/tags.js'
import { direction as directionArr, difficulty, questionType } from '@/api/hmmm/constants.js'
import { add as fetchAddQuestion, detail as fetchQuestionInfo, update as fetchUpdate } from '@/api/hmmm/questions.js'

// 自定义富文本框的工具栏
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  ['clean'], // 清除文本格式-----['clean']
  ['link', 'image'] // 链接、图片、视频-----['link', 'image', 'video']
]

const initForm = {
  subjectID: '', // 学科
  catalogID: '', // 目录
  enterpriseID: '', // 企业
  province: '', // 城市
  city: '', // 地区
  direction: '', // 方向
  questionType: 1, // 题型
  difficulty: 1, // 难度
  question: '', // 题干
  options: [
    {
      code: 'A', // 代码
      title: '', // 标题
      img: '', // 图片URL
      isRight: false // 是否正确答案
    },
    {
      code: 'B', // 代码
      title: '', // 标题
      img: '', // 图片URL
      isRight: false // 是否正确答案
    },
    {
      code: 'C', // 代码
      title: '', // 标题
      img: '', // 图片URL
      isRight: false // 是否正确答案
    },
    {
      code: 'D', // 代码
      title: '', // 标题
      img: '', // 图片URL
      isRight: false // 是否正确答案
    }
  ],
  videoURL: '', // 解析视频
  answer: '', // 答案解析
  remarks: '', // 题目备注
  tags: [] // 试题标签
}

export default {
  name: 'QuestionsNew',
  data () {
    return {
      cardTitle: '试题录入',
      form: { ...initForm },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      // 富文本工具栏设置
      editorOption: {
        placeholder: '请输入...',
        modules: {
          toolbar: toolbarOptions
        }
      },
      radioChecked: '单选',
      heckboxChecked: [''],
      currentRadio: '', // 单选状态下，当前选中的值
      imageUrl: '',
      subjectList: [], // 学科列表
      directionList: [], // 目录列表
      provinceList: [],
      companyList: [],
      cityList: [],
      tagList: [],
      catalogList: [], // 目录列表
      oldProvince: '', // 上一个城市名
      oldSubjectId: '',
      difficultyArr: [], // 难度
      questionTypeArr: []// 题型
    }
  },
  created () {
    this.initDatas()
  },
  methods: {
    // 初始化数据
    initDatas () {
      this.getSubjectList()
      this.getCompanyList()
      this.getProvinceList()
      this.directionList = directionArr
      this.difficultyArr = difficulty
      this.questionTypeArr = questionType

      // 有传参，说明是试题修改
      // console.log(this.$route.query)
      if (this.$route.query.id) {
        this.cardTitle = '试题修改'
        this.getQuestionsDetail(this.$route.query.id)
      }
    },
    // 确认提交
    onSubmit () {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            let tags = this.form.tags
            // 如果是数组，需要转为字符串
            if (tags instanceof Array) {
              tags = this.form.tags.length > 0 ? this.form.tags.join(',') : ''
            }
            // questionType,difficulty数字转字符串
            this.form.questionType = this.form.questionType.toString()
            this.form.difficulty = this.form.difficulty.toString()

            if (this.cardTitle === '试题录入') {
              await fetchAddQuestion({ ...this.form, tags })
            } else {
              await fetchUpdate({ ...this.form, tags })
            }
            this.$message.success(this.cardTitle + '成功')
            this.$refs.formRef.resetFields()
            this.form = { ...initForm }
            // 跳转到基础题库列表
            if (this.cardTitle === '试题录入') {
              this.$router.push({ path: '/questions/list' })
            } else {
              this.$router.back()
            }
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    // 新增选项与答案
    addOption () {
      const length = this.form.options.length
      // 大写字母A-Z对应的ASCII码值是65-90
      // 小写字母a-z对应的ASCII码值是97-122
      const letter = String.fromCharCode(65 + length)
      const option = {
        code: letter, // 代码
        title: '', // 标题
        img: '', // 图片URL
        isRight: false // 是否正确答案
      }
      this.form.options.push(option)
    },
    // 获取学科列表
    async getSubjectList () {
      try {
        const res = await fetchSubjects()
        this.subjectList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取企业列表
    async getCompanyList () {
      try {
        const obj = {
          page: 1,
          pagesize: 50

        }
        const res = await fetchCompanys(obj)
        this.companyList = res.data.items
        // console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取城市列表
    getProvinceList () {
      const res = fetchProvinces()
      this.provinceList = res
    },

    // 选择学科
    async changeSubject (id) {
      // id 学科id
      // console.log(id)
      if (id !== this.oldSubjectId) {
        // 清空数据
        this.form.catalogID = ''
        this.form.tags = ''
      }
      try {
        // 获取标签
        const res = await fetchTags({ subjectID: id })
        this.tagList = res.data
        // 获取目录
        const res2 = await fetchDirectorys({ subjectID: id })
        this.catalogList = res2.data
      } catch (error) {
        console.log(error)
      }
    },
    // 选择省份
    changeProvince (val) {
      if (val !== this.oldProvince) {
        // el-select 清空
        this.form.city = ''
      }
      this.cityList = fetchCitys(val)
      this.oldProvince = val
    },
    // 单选change事件
    radioChange (val) {
      this.form.options.forEach(item => {
        if (item.code === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // 题型改变,选中状态清空
    questionTypeChange (val) {
      this.currentRadio = ''
      this.form.options.forEach(item => {
        item.isRight = false
      })
    },
    // 获取问题详情
    async getQuestionsDetail (id) {
      const res = await fetchQuestionInfo({ id })
      // console.log(res)
      this.form = res.data

      this.changeDataOfForm()
    },
    // 问题详情数据处理
    changeDataOfForm () {
      // 文字转为对应的数字
      // 判断是否是数字字符串
      let isNumString = true
      this.difficultyArr.forEach(item => {
        if (item.label === this.form.difficulty) {
          this.form.difficulty = item.value
          isNumString = false
        }
      })
      if (isNumString) {
        this.form.difficulty = Number(this.form.difficulty)
        isNumString = true
      }

      this.questionTypeArr.forEach(item => {
        if (item.label === this.form.questionType) {
          this.form.questionType = item.value
          isNumString = false
        }
      })

      if (isNumString) {
        this.form.questionType = Number(this.form.questionType)
      }
      // 选中状态转为布尔型
      this.form.options.forEach(item => {
        item.isRight = Boolean(item.isRight)
      })

      // 单选时，获取当前选中选项的code
      if (this.form.questionType === 1) {
        this.form.options.forEach(item => {
          if (item.isRight) this.currentRadio = item.code
        })
      }
      // 选项重新排序
      this.form.options.sort(function (a, b) {
        const num1 = a.code.charCodeAt()
        const num2 = b.code.charCodeAt()
        return (num1 - num2)
      })

      // 保证当前新获得的学科id和oldSubjectId一致，避免changeSubject时的数据清空
      this.oldSubjectId = this.form.subjectID
      this.oldProvince = this.form.province

      // 获取目录，标签列表
      this.changeSubject(this.form.subjectID)
      // 获取地区列表
      this.changeProvince(this.form.province)
      if (this.form.tags.length > 0) {
        const tagsArr = this.form.tags.split(',')
        // 有人上传的是id拼接的字符串，有人上传的是文本拼接的字符串，这里需要处理一下
        // 如果是id拼接的字符串
        const labelArr = []

        this.tagList.forEach(item => {
          if (tagsArr.inclides(item.value)) {
            labelArr.push(item.label)
          }
        })

        this.form.tags = tagsArr.length === labelArr.length ? labelArr : tagsArr
      }

      // 异步更新
      this.$nextTick(() => {
        // console.log('页面返回最顶端')
        window.scrollTo(0, 0)
      })
    },
    // 富文本验证提示的取消
    changeQuillEditor (val) {
      if (val === 'answer') {
        if (this.form.answer.trim() === '') {
          this.$refs.formRef.validateField('answer')
        } else {
          this.$refs.answerRef.clearValidate() // clearValidate()取消验证方法
        }
      } else {
        if (this.form.question.trim() === '') {
          this.$refs.formRef.validateField('question')
        } else {
          this.$refs.questionRef.clearValidate() // clearValidate()取消验证方法
        }
      }
    }

  },

  components: {
    QuestionsNewOption
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 20px;
  // 样式穿透
  /deep/ .ql-editor {
    height: 240px;
  }
  .option_item {
    display: flex;
    justify-content: start;
    align-items: center;
    margin-bottom: 10px;
    /deep/ .el-radio {
      width: 50px;
      margin-right: 1px;
    }

    /deep/ .el-checkbox {
      width: 50px;
      margin-right: 1px;
    }
  }
}
</style>
